package org.lep.leetcode.datastructure.tree.lowestcommonancestor;

/**
 * https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree
 *
 * @author lverpeng
 * @since 2020/3/11
 */
public class LowestCommonAncestorOfBinarySearchTree {
    /**
     * 利用二叉搜索树的特点：左子树 < root < 右子树
     * 有公共父节点几种情况：
     * 1. p，q都在左子树上，针对左节点遍历
     * 2. p，q都在右子树上，针对右节点遍历
     * 3. p，q左右子树各一个，说明当前节点就是公共祖先
     *
     * 时间：O(N)，最坏需要全部遍历所有节点
     * 空间：O(N)，空间主要是递归带来的
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        int pVal = p.val;
        int qVal = q.val;
        int rVal = root.val;
        if (rVal > pVal && rVal > qVal) {
            return lowestCommonAncestor(root.left, p, q);
        } else if (rVal < pVal && rVal < qVal) {
            return lowestCommonAncestor(root.right, p, q);
        } else {
            return root;
        }
    }

    /**
     * 时间：O(N）
     * 空间：O(1)
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        int pVal = p.val;
        int qVal = q.val;
        int rVal;
        while (root != null) {
            rVal = root.val;
            if (rVal > pVal && rVal > qVal) {
                root = root.left;
            } else if (rVal < pVal && rVal < qVal) {
                root = root.right;
            } else {
                return root;
            }
        }
        return null;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}
